import React, {Component} from 'react';
import {
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  Image,
  TouchableOpacity,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import SocketIO from 'socket.io-client';
import AsyncStorage from '@react-native-community/async-storage';
import RNBootSplash from 'react-native-bootsplash';

import Api from '../Api';
import GroupWait from '../assets/group_wait.png';
import GroupWait2 from '../assets/group_wait2.png';
import GroupDoing from '../assets/group_doing.png';
import GroupDone from '../assets/group_done.png';
import GroupRepair from '../assets/group_repair.png';
import GroupVideo from '../assets/group_video.png';
import ListItem from '../components/ListItem';

let isCurrentScene = true;
export default class GroupScreen extends Component {
  constructor(props) {
    super(props);
    this.state = {count: {}};
  }

  componentDidMount() {
    this.getListCount();
    // 隐藏启动图
    RNBootSplash.hide({duration: 1000});
  }

  /**
   * 1.初始化socket
   */
  UNSAFE_componentWillReceiveProps(nextProps) {
    const {user} = nextProps;
    if (user && !this.state.socket) {
      const socket = SocketIO(Api.SOCKET_URL, {
        transports: ['websocket']
        // forceNode: true,
      });
      this.setState({socket});
      socket
        .on('connect', () => {
          socket.emit('join', 'notify', (err, room) => {
            Object.keys(room.clients).forEach(function(id) {
              socket.emit('message', {
                to: id,
                from: socket.id,
                broadcaster: socket.id,
                type: 'username',
                roomType: 'message',
                playroad: {
                  username: user.username,
                },
              });
            });
          });
        })
        .on('message', msg => {
          if (msg.type == 'usernames') {
            this.hoster = msg.from;
            socket.emit('message', {
              to: this.hoster,
              from: socket.id,
              broadcaster: socket.id,
              type: 'username',
              roomType: 'message',
              playroad: {
                username: nextProps.user.username,
              },
            });
          }
        });
    }
    if (this.props.enterTime !== nextProps.enterTime) {
      this.timer && clearTimeout(this.timer);
      this.getListCount();
    } else if (user && !this.hasLoad) {
      this.timer && clearTimeout(this.timer);
      this.getListCount();
    }
  }
  // tabbar 页面componentWillUnmount不会触发
  //   componentWillUnmount() {
  //     const {socket} = this.state;
  //     this.timer && clearTimeout(this.timer);
  //     socket &&
  //       socket.emit('message', {
  //         to: this.hoster,
  //         from: socket.id,
  //         broadcaster: socket.id,
  //         type: 'logout',
  //         roomType: 'message',
  //       });
  //   }

  static onEnter() {
    console.log('===onEnter');
    isCurrentScene = true;
    Actions.refresh({
      enterTime: new Date(),
    });
  }

  static onExit() {
    console.log('===onExit');
    isCurrentScene = false;
    this.timer && clearTimeout(this.timer);
  }

  async getListCount() {
    if (!isCurrentScene) return;
    // data: [{"count": 1, "status": 200}, {"count": 2, "status": 700}]
    const data = await Api.worksheetcount();
    if (Array.isArray(data)) {
      this.hasLoad = true;
      let count = {};
      if (data) {
        for (var i = 0; i < data.length; i++) {
          count[data[i].status + ''] = data[i].count;
        }
        this.setState({
          count,
        });
        // 每隔1s轮询数据
        this.timer = setTimeout(() => {
          this.getListCount();
        }, 1000);
      }
    }
  }

  handlePressVideo = () => {
    if (this.state.socket && !this.state.socket.connected) {
      this.state.socket.connect();
    }
    this.state.socket.emit('message', {
      to: this.hoster,
      from: this.state.socket.id,
      broadcaster: this.state.socket.id,
      type: 'call',
      roomType: 'message',
      playroad: {
        username: this.props.user.username,
      },
    });
    Actions.video({
      room: this.state.socket.id,
      socket: this.state.socket,
      hoster: this.hoster,
    });
  };

  render() {
    const {count} = this.state;
    return (
      <ScrollView
        style={{
          height: '100%',
        }}>
        <StatusBar barStyle="light-content" backgroundColor="#5096fc" />
        <ListItem
          title="待接单"
          icon={GroupWait}
          count={count['200'] || 0}
          onPress={() => {
            Actions.worksheet({
              status: 200,
            });
          }}
          style={{marginTop: 15}}
        />
        <ListItem
          title="待到场"
          icon={GroupWait2}
          count={count['300'] || 0}
          onPress={() => {
            Actions.worksheet({
              status: 300,
            });
          }}
        />
        <ListItem
          title="施工中"
          icon={GroupDoing}
          count={count['400'] || 0}
          onPress={() => {
            Actions.worksheet({
              status: 400,
            });
          }}
        />
        <ListItem
          title="已完成"
          icon={GroupDone}
          iconStyle={{width: 24, height: 24}}
          count={count['700'] || 0}
          onPress={() => {
            Actions.worksheet({
              status: 700,
            });
          }}
        />
        <ListItem
          title="代报修"
          icon={GroupRepair}
          showBadge={false}
          onPress={() => {
            Actions.addSheet();
          }}
        />
        <ListItem
          title="视频专家"
          icon={GroupVideo}
          showBadge={false}
          onPress={this.handlePressVideo}
        />
      </ScrollView>
    );
  }
}
